//
//  HEDoctorServerComfireViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/18.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEDoctorServerComfireViewController.h"
#import "HEDocOrderHeadCell.h"
#import "HEDocOrderInfoCell.h"
#import "HEOrderTitleCell.h"
#import "HEOrderPayCell.h"
#import "HECreateOrderResponse.h"
#import "HEWxPayReqModel.h"
#import "HEPayResultResViewController.h"
#import "HEOrderDetailsViewController.h"
#import "HEAddHealthReportViewController.h"
#import "HEDoctorPrivateSignViewController.h"
#import "HETWViewController.h"
#import "HEQRPayView.h"
#import "HEOrderTabBarView.h"
#import "HEReportSelectCell.h"
#import "HEBindUserModel.h"
#import "HEPreferModel.h"
#import "HEPreferPopView.h"
#import "HEReportTitleInputCell.h"
#import "HEDocOrderAddAddressCell.h"
#import "HEAddressViewController.h"
#import "HEDocOrderAddressCell.h"
#import "HEDocOrderTransFeesCell.h"
#import "HETranspFeesModel.h"
#import "HEReceiveAddressModel.h"

@interface HEDoctorServerComfireViewController ()<UITableViewDelegate, UITableViewDataSource, HEReportSelectCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray <HEDoctorCommentModel *> *commentList;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@property (nonatomic, strong) UIButton *bottomView;

@property (nonatomic, strong) HEOrderModel * order;

@property (nonatomic, strong) HEOrderTabBarView *tabbar;

@property (nonatomic, strong) NSMutableArray <HEBindUserModel *> *bindUsers;

@property (nonatomic, strong) GDFiterCellModel *selectPersonModel;
@property (nonatomic, strong) GDFiterCellModel *preferModel;

@property (nonatomic, strong) HEPreferPopView *preferPopView;
@property (nonatomic, strong) HEPreferModel *prefer;

@property (nonatomic, strong) HETranspFeesModel *transpFee;
@property (nonatomic, strong) NSDecimalNumber *preferAfterPrice; // 商品满减优惠后的价格

@end

@implementation HEDoctorServerComfireViewController

- (HETranspFeesModel *)transpFee {
    if (!_transpFee) {
        _transpFee = [HETranspFeesModel new];
        _transpFee.transFees = [NSDecimalNumber decimalNumberWithString:@"0"];
    }
    return _transpFee;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPayFailure object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"确认信息";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFialure) name:KNotificationPayFailure object:nil];
  
    self.preferAfterPrice = [NSDecimalNumber decimalNumberWithString:_price];

    [self initUI];
    [self initCell];
    [self initTabBarView];

    [self loadPaydata];
    [self getBindUserData];
    [self getDiscountsData];
    
    if (self.orderRequest.channel == HEChannelTypeDoctorTeam) {
        [self loadAddrresData];
    }
}
 
- (void)initUI {
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = KWhiteColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];
    NSMutableArray *classArr = [NSMutableArray array];
       
    NSArray *paramsTitles = @[@"支付类型：", @"规格：", @"签约人"];
  
    // 医生信息
    GDFiterCellModel *doctorModel = [GDFiterCellModel new];
    doctorModel.cellKlass = HEDocOrderHeadCell.class;
    
    // 显示地址
    GDFiterCellModel *addressModel = [GDFiterCellModel new];
    addressModel.cellKlass = HEDocOrderAddressCell.class;

    // 添加地址
    GDFiterCellModel *addModel = [GDFiterCellModel new];
    addModel.cellKlass = HEDocOrderAddAddressCell.class;
    addModel.cellDisplayType = self.orderRequest.channel == HEChannelTypeDoctorTeam? GDCellDisplayShow:GDCellDisplayNone;
   
    // 选择签约人
    GDFiterCellModel *selectPersonModel = [GDFiterCellModel new];
    selectPersonModel.cellDisplayType = _isSelectSign ? GDCellDisplayShow : GDCellDisplayNone;
    selectPersonModel.cellKlass = HEReportSelectCell.class;
    selectPersonModel.leftTitle = @"签约人";
    selectPersonModel.placeHolder = @"选择签约人";
    selectPersonModel.tableKey = @"bd_name";
    selectPersonModel.leftTitleColor = CNavBgColor;
    selectPersonModel.contentColor = CNavBgColor;
    _selectPersonModel = selectPersonModel;
    
    // 交通费用
    GDFiterCellModel *transFeeModel = [GDFiterCellModel new];
    transFeeModel.cellKlass = HEDocOrderTransFeesCell.class;
    transFeeModel.cellDisplayType = self.orderRequest.channel == HEChannelTypeDoctorTeam && self.visit? GDCellDisplayShow:GDCellDisplayNone;
    transFeeModel.cellType = GDFiterCellTypeGoodTransFeesInfo;
    
    // 优惠选项
    GDFiterCellModel *preferModel = [GDFiterCellModel new];
    preferModel.cellDisplayType = _isShowPrefer ? GDCellDisplayShow : GDCellDisplayNone;
    preferModel.cellType = GDFiterCellTypeGoodPrefer;
    preferModel.cellKlass = HEReportTitleInputCell.class;
    preferModel.showArrow = YES;
    preferModel.leftTitle = @"优惠：";
    preferModel.placeHolder = @"暂无优惠";
    preferModel.enable = NO;
    preferModel.tableKey = @"pf_title";
    preferModel.contentColor = CPriceColor;
    preferModel.leftFont = DYBlodFont(18);
    preferModel.contentFont = DYBlodFont(18);
    _preferModel = preferModel;
 
    // 支付参数
    GDFiterCellModel *infoModel = [GDFiterCellModel new];
    infoModel.cellKlass = HEDocOrderInfoCell.class;
    infoModel.cellType = GDFiterCellTypeDoctorOrderItem;
    
    // 支付头部
    GDFiterCellModel *headModel = [GDFiterCellModel new];
    headModel.cellKlass = HEOrderTitleCell.class;
    headModel.leftTitle = @"支付方式";
    headModel.cellType = GDFiterCellTypeDoctorOrderHead;

    // 支付
    GDFiterCellModel *paycelModel = [GDFiterCellModel new];
    paycelModel.cellKlass = HEOrderPayCell.class;
    paycelModel.cellType = GDFiterCellTypeOrderPay;
    
    
    // 添加的时候注意顺序，暂未对顺序做处理
    NSArray *modelArr = @[doctorModel, addModel, selectPersonModel, addressModel, infoModel, transFeeModel, preferModel, headModel, paycelModel].mutableCopy;
    [self.tableView mc_registerAllCellByFiterModels:modelArr];
    
    classArr = @[doctorModel, addModel, selectPersonModel, infoModel, transFeeModel, preferModel, headModel, paycelModel].mutableCopy;
    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
         
        // 隐藏未达到条件的cell
         if (model.cellDisplayType == GDCellDisplayNone) {
             continue;
         }
        // 添加地址
         else if ([model.cellKlass isEqual:HEDocOrderAddressCell.class]) {
             [secs addObject:model];
         }
         else if (model.cellType == GDFiterCellTypeDoctorOrderItem) {
             int i = 0;
             for (NSString * item in _comfireModel.payParams) {
                 // 支付参数
                 GDFiterCellModel *infoItem = [GDFiterCellModel new];
                 infoItem.cellKlass = HEDocOrderInfoCell.class;
                 infoItem.cellType = GDFiterCellTypeDoctorOrderItem;
                 infoItem.leftTitle = paramsTitles[i];
                 if ( i == 2) {
                     infoItem.leftTitleColor = CNavBgColor;
                     infoItem.contentColor = CNavBgColor;
                 }
                 [secs addObject:infoItem];
                 i++;
             }
         }
         else if (model.cellType == GDFiterCellTypeGoodTransFeesInfo ||
                  model.cellType == GDFiterCellTypeGoodPrefer) {
             secs = _sections.lastObject;
             [secs addObject: model];
             continue;
         }
         else if (model.cellType == GDFiterCellTypeOrderPay) {
//             for (HEPaymentModel *pay in self.comfireModel.orderPayments) {
//                 GDFiterCellModel *payModel = [GDFiterCellModel new];
//                 payModel.cellKlass = HEOrderPayCell.class;
//                 payModel.cellType = GDFiterCellTypeOrderPay;
//                 [secs addObject:payModel];
//             }
         }
         else {
            [secs addObject:model];
        }
         
        [_sections addObject: secs];
     }
    
    [_tableView reloadData];
}

//- (void)initTabBarView {
//    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
//    _bottomView = bottomView;
//    [self.view addSubview:bottomView];
//    bottomView.backgroundColor = CNavBgColor;
//    _bottomView.titleLabel.font = DYBlodFont(18);
//    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
//    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
//
//    [bottomView setTitle:[NSString stringWithFormat:@"去支付%@元", [NSDecimalNumber rounding:_price afterPoint:2]] forState:UIControlStateNormal];
//
//    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.equalTo(self.view);
//        make.height.mas_offset(49);
//        make.bottom.offset(-ZXSafeAreaBottom);
//    }];
//}

#pragma mark - load Data
- (void)getBindUserData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[UserManager sharedUserManager].curUserInfo.id forKey:@"gid"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetBindUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [self.bindUsers removeAllObjects];
        [weakSelf.bindUsers addObjectsFromArray:[HEBindUserModel mj_objectArrayWithKeyValuesArray:response.data]];
        
        UserInfo *archiveInfo = [UserManager sharedUserManager].curUserInfo;
        HEBindUserModel *ower = [HEBindUserModel new];
        ower.id = archiveInfo.id;
        ower.realname = archiveInfo.realname;
        ower.relations = @"本人";
        [weakSelf.bindUsers insertObject:ower atIndex:0];
        
        NSMutableArray *strs = @[].mutableCopy;
        for (HEBindUserModel *model in weakSelf.bindUsers) {
            [strs addObject:[NSString stringWithFormat:@"%@(%@)", model.realname, model.relations]];
        }
        weakSelf.selectPersonModel.pickerDataArray = strs;
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)getDiscountsData {
    
    KWeakSelf
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KgetDiscounts parameters:@{} success:^(id  _Nonnull responseObject) {
        DLog(@"%@",[responseObject mj_JSONString])
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray *arr = [HEPreferModel mj_objectArrayWithKeyValuesArray:response.data];
        self.prefer = arr.firstObject;
        if (self.prefer) {
            [self calcPrefer];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)loadAddrresData {

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KaddressList parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
 
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray *addrss = [HEReceiveAddressModel mj_objectArrayWithKeyValuesArray:response.data];
 
        for (HEReceiveAddressModel *model in addrss) {
            if (model.defaultStatus) {
                [self selectAddressWithModel: model];
                break;
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
         
    }];
}

- (void)loadTranpFeeData {
    
    if (self.orderRequest.channel != HEChannelTypeDoctorTeam || !self.visit) {
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.latitude] forKey:@"lat"];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.longitude] forKey:@"lng"];
    [params setObject:[NSNumber numberWithLong: _orderRequest.goodsId.longValue] forKey:@"productId"];
    [params setObject:[NSNumber numberWithLong: _orderRequest.skuId] forKey:@"attrId"];

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KtranspFee parameters:params success:^(id  _Nonnull responseObject) {
        
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            self.transpFee = [HETranspFeesModel mj_objectWithKeyValues:response.data];
            self.formModel.od_transFee = self.transpFee;
            [self calcPayPric];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)calcPrefer {
    self.formModel.pf_title = self.prefer.name;
    HEPreferRule *rule = self.prefer.Krules.firstObject;
    
    // 没有优惠规则
    if (!rule) {
        [self disablePrefer];
        return;
    }

    // 是否支持优惠
    if (self.prefer.activiGoods == 1) { // 按类别
        if (![self enablePreferByCategory]) {
            [self disablePrefer];
            return;
        }
    }else if (self.prefer.activiGoods == 2) { // 部分商品
        if (![self enablePreferByGood]) {
            [self disablePrefer];
            return;
        }
    }
    // 原价
    NSDecimalNumber *oldPrice = [NSDecimalNumber decimalNumberWithString: _price];
    
    // 满10元
    NSDecimalNumber *fullPrice = [NSDecimalNumber decimalNumberWithString: rule.fullPrice];
    
    // 减1.5元
    NSDecimalNumber *reducePrice = [NSDecimalNumber decimalNumberWithString: rule.reducePrice];

    // 计算折扣率 (10 - 1.5) / 10
    NSDecimalNumber *discount = [[fullPrice decimalNumberBySubtracting:reducePrice] decimalNumberByDividingBy:fullPrice];
    
    // 保留2位小数
    NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    
    // 计算折后价 [ 原价 * 折扣率 ]
    NSDecimalNumber *payPrice = [oldPrice decimalNumberByMultiplyingBy:discount withBehavior: roundUp];
    
    NSString *precision = [NSString stringWithFormat:@"%%.%df", 2];
    _preferAfterPrice = payPrice;

//    NSString *precision = [NSString stringWithFormat:@"%%.%df", 2];
//    _preferPrice = [NSString stringWithFormat:precision, payPrice.doubleValue];

    [self calcPayPric];
}

- (void)calcPayPric {
    // 合计 = 商品总计 + 交通费
    NSDecimalNumber *tot = [_preferAfterPrice decimalNumberByAdding: self.transpFee.transFees];
    self.tabbar.totalPrice = [tot keepTwo];
    
//    [self.tableView.fd_keyedHeightCache invalidateAllHeightCache];
    [self.tableView reloadData];
}

// 所选类别服务是否能享优惠
- (BOOL)enablePreferByCategory {
    BOOL enable = NO;
    for (HEPreferGood *model in self.prefer.KgoodsDs) {
        if (model.id == _serviceCategoryId.integerValue) {
            enable = YES;
            break;
        }
    }
    return enable;
}

// 所选商品是否能享优惠
- (BOOL)enablePreferByGood {
    BOOL enable = NO;
    for (HEPreferGood *model in self.prefer.KgoodsDs) {
        if (model.id == _orderRequest.goodsId.integerValue) {
            enable = YES;
            break;
        }
    }
    return enable;
}

- (void)disablePrefer {
    [self calcPayPric];

    self.formModel.pf_title = @"暂无优惠";
    [self.tableView reloadData];
}

- (void)initTabBarView {
    HEOrderTabBarView *tabbar = [[HEOrderTabBarView alloc] initWithFrame:CGRectZero type:HEOrderTabBarViewTypeDefualt];
    tabbar.delegate = self;
    [self.view addSubview:tabbar];
    self.tabbar = tabbar;
    
    tabbar.totalPrice = [NSDecimalNumber rounding:_price afterPoint:2];
    
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

#pragma mark - HEOrderTabBarViewDelegate
- (void)submitOrderHandler {
    if (self.formModel.order_payType == nil) {
        [Dialog toast:@"请选择支付方式~" delay:2.0];
        return;
    }
    
    if (_isSelectSign) {
        if ([DYTools isBlankString:_orderRequest.memberId]) {
            [Dialog toast:@"请选择签约人" delay:2.0];
            return;
        }
    }

    [self crateOrder];
}

- (void)crateOrder {
    
//    HECreateOrderRequest *request = [HECreateOrderRequest new];
//    request.orderType = HEOrderTypeGeneral;
//    request.doctor_id = _userModel.user_id;
//    request.total = 1;
//    request.goodsId = _selectServerModel.goods_id;
//    request.channel = _selectServerModel.channel;
//    request.skuId = _selectServerModel.attr_id;
//    request.source = HEOrderSourceTypeiOS;
////    request.addressId = self.formModel.order_addres.id;
//    request.type = HESubmitPreviewTypeByGoodsDetails;
//
//    HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
//    extra.planId = _planId;
//    extra.order_type = _selectServerModel.channel;
//    extra.inst_id = _inst_id;
//    extra.private_doctor_form_id = _private_doctor_form_id;
//
//    extra.doctor_info = [DoctorInfo new];
//    extra.doctor_info.user_id = _userModel.user_id;
//    extra.doctor_info.post_name = _userModel.post_name;
//    extra.doctor_info.avatar = _userModel.avatar;
//    extra.doctor_info.depart_name = _userModel.depart_name;
//    extra.doctor_info.realname = _userModel.realname;
//    request.extras = [extra mj_JSONString];

    if (self.orderRequest.channel == HEChannelTypeDoctorTeam) {
        if (!self.orderRequest.addressId) {
            [Dialog toastBottom:@"请选择上门服务地址!"];
            return;
        }
    }
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KgenerateOrder parameters:_orderRequest success:^(id  _Nonnull responseObject) {

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            HECreateOrderResponse *data = [HECreateOrderResponse mj_objectWithKeyValues:response.data];
            self.order = data.order;
            
            // 发起支付
            if ([self.formModel.order_payType isEqualToString:KWxPayCode]) {
                [self createWxPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KAliPayCode]) {
                [self createAliPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KQRPayCode]) {
                [self showQRPay];
            }
            
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark 二维码支付
- (void)showQRPay {
    NSString *token = [[UserManager sharedUserManager] getToken];
    KWeakSelf
    [HEQRPayView showWithURL: [NSString stringWithFormat:@"https://www.honglutec.com/oldPay/codePage.html?appSource=%d&orderId=%ld&payPlatform=%@&token=%@&providerPay=%d", KAppSource, self.order.id, KPayPlatform, token, _order.storeId == 1 ? 0 : 1] cancelBlock:^{
        [weakSelf payFialure];
    }];
}

#pragma mark 请求支付宝支付串
- (void)createAliPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    NSString *url = _order.storeId == 1 ? KAliAppPay : KAliAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [[HEPayManager sharedManager] senAliPayRequest:response.data];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
#pragma mark 请求微信支付串
- (void)createWxPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KWxAppPay : KWxAppProPay;

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters: dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        HEWxPayReqModel *wxModel = [HEWxPayReqModel mj_objectWithKeyValues:[DYTools getContainersObjectFromJsonString:response.data]];
            
        PayReq* req = [[PayReq alloc] init];
        req.partnerId = wxModel.partnerid;
        req.prepayId = wxModel.prepayid;
        req.nonceStr = wxModel.noncestr;
        req.timeStamp = wxModel.timestamp.unsignedIntValue;
        req.package = wxModel.package;
        req.sign = wxModel.sign;
        [WXApi sendReq:req completion:^(BOOL success) {
            if (!success) {
                [Dialog toastBottom:@"支付失败~"];
                [self payFialure];
            }
        }];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - 支付回调
- (void)paySuccess {
        
    // 支付成功，删除订单预览页，跳转到订单详请页
     HEPayResultResViewController *vc = [HEPayResultResViewController new];
      // 删除当前页
     [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
      NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
         int i = 0;
         for (UIViewController *vc in marr) {
             if ([vc isKindOfClass:[HEDoctorServerComfireViewController class]]) {
                  [marr removeObject:vc];
                  break;
             }else if ([vc isKindOfClass:[HEAddHealthReportViewController class]]) {
                  [marr removeObjectAtIndex:i+1];
                  [marr removeObject:vc];
                  break;
             }else if ([vc isKindOfClass:[HEDoctorPrivateSignViewController class]]) {
                 [marr removeObjectAtIndex:i+1];
                 [marr removeObject:vc];
                 break;
            }else if ([vc isKindOfClass:[HETWViewController class]]) {
                [marr removeObjectAtIndex:i+1];
                [marr removeObject:vc];
                break;
           } 
             i++;
         }
      self.navigationController.viewControllers = marr;
     }];
}

- (void)payFialure {

    // 放弃支付或者支付失败，删除订单预览页，跳转到订单详请页
    HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
    vc.orderId = self.order.id;
     // 删除当前页
    [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
     NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
        int i = 0;
        for (UIViewController *vc in marr) {
            if ([vc isKindOfClass:[HEDoctorServerComfireViewController class]]) {
                 [marr removeObject:vc];
                 break;
            }else if ([vc isKindOfClass:[HEAddHealthReportViewController class]]) {
                 [marr removeObjectAtIndex:i+1];
                 [marr removeObject:vc];
                 break;
            }else if ([vc isKindOfClass:[HEDoctorPrivateSignViewController class]]) {
                [marr removeObjectAtIndex:i+1];
                [marr removeObject:vc];
                break;
           }else if ([vc isKindOfClass:[HETWViewController class]]) {
               [marr removeObjectAtIndex:i+1];
               [marr removeObject:vc];
               break;
          }
           i++;
        }
     self.navigationController.viewControllers = marr;
    }];
}



#pragma mark -
 
- (void)loadPaydata {

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:Kpaymentlist parameters:@{@"appSource":@(KAppSource)} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        self.comfireModel.orderPayments = [HEPaymentModel mj_objectArrayWithKeyValuesArray:response.data];
        if (self.comfireModel.orderPayments.count > 0) {
            HEPaymentModel *firstModel = self.comfireModel.orderPayments.firstObject;
            firstModel.isChoose = YES;
            self.formModel.order_payType = firstModel.code;
        }
        
        NSMutableArray *secs = _sections.lastObject;

        for (HEPaymentModel *pay in self.comfireModel.orderPayments) {
            GDFiterCellModel *payModel = [GDFiterCellModel new];
            payModel.cellKlass = HEOrderPayCell.class;
            payModel.cellType = GDFiterCellTypeOrderPay;
            [secs addObject:payModel];
        }

        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.formModel = self.formModel;
    [cell configCellWithModel:_comfireModel fiterModel:fiterModel indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        cell.formModel = self.formModel;
        [cell configCellWithModel:self.comfireModel fiterModel:fiterModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
     GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeOrderPay) {
        HEPaymentModel *payModel = self.comfireModel.orderPayments[indexPath.row];
        self.formModel.order_payType = payModel.code;
        [self changeSelectPayType:indexPath.row];
    }else if (fiterModel.cellType == GDFiterCellTypeGoodPrefer) {
        HEPreferPopView *manageView = [HEPreferPopView new];
        manageView.model = self.prefer;
        [manageView show];
    }
}

- (void)changeSelectPayType:(NSInteger)index {
    
    for (int i = 0; i < self.comfireModel.orderPayments.count; i++) {
        HEPaymentModel *payModel = self.comfireModel.orderPayments[i];
        if (index == i) {
            payModel.isChoose = YES;
        }else {
            payModel.isChoose = NO;
        }
    }
    
    [_tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.lastObject;
    
    if (fiterModel.cellType == GDFiterCellTypeOrderPay) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}

 
- (void)changeTabbarView {
  
}

#pragma mark - HEReportSelectCellDelegate
- (void)cellSelectHandler:(HEReportSelectCell *)cell index:(NSInteger)index {
    _orderRequest.memberId = self.bindUsers[index].id;
}

#pragma mark - HEDocOrderAddAddressCellDelegate HEDocOrderAddressCellDelegate
- (void)orderAddAddressSelect {
    [self toSelectAddressVC];
}

- (void)orderSelectAddressSelect {
    [self toSelectAddressVC];
}

- (void)toSelectAddressVC {
    HEAddressViewController *vc = [HEAddressViewController new];
    vc.type = HEAddressIntoTypeToSelect;
    [vc selectAddress:^(HEReceiveAddressModel * _Nonnull model) {
        [self selectAddressWithModel:model];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectAddressWithModel:(HEReceiveAddressModel *)model {
    self.formModel.order_addres = model;

    self.orderRequest.addressId = model.id;
    GDFiterCellModel *addressModel = [GDFiterCellModel new];
    addressModel.cellKlass = HEDocOrderAddressCell.class;
    
    NSMutableArray *sec2 = self.sections[1];
    [sec2 replaceObjectAtIndex:0 withObject:addressModel];
    [self.tableView reloadData];
    
    [self loadTranpFeeData];
}
 
- (NSMutableArray<HEBindUserModel *> *)bindUsers {
    if (!_bindUsers) {
        _bindUsers = @[].mutableCopy;
    }
    return _bindUsers;
}
@end
